package bookshop.utils;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthenticationFilter implements Filter {

	@Override
	public void destroy() {

		System.out.println("AuthenticationFilter is destoried now!");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hreq = (HttpServletRequest) request;
		HttpServletResponse hrep = (HttpServletResponse) response;

		hreq.setCharacterEncoding("utf-8");
		hrep.setCharacterEncoding("utf-8");
		
		String fileName = hreq.getRequestURI().substring(
				hreq.getRequestURI().lastIndexOf("/") + 1);

		if (fileName.indexOf(".gif") != -1 || fileName.indexOf(".jpg") != -1
				|| fileName.indexOf(".css") != -1
				|| fileName.indexOf("index.jsp") != -1
				|| fileName.indexOf("login.jsp") != -1
				|| fileName.indexOf("securityMgr") != -1	
				|| fileName.indexOf("ddcremoteworkflow") != -1	
				|| fileName.indexOf("homeMgr") != -1	
				|| fileName.indexOf("workflow") != -1
				|| fileName.indexOf("customer") != -1
				|| fileName.indexOf("temp.jsp") != -1
				|| fileName.indexOf("myDD") != -1
				|| fileName.indexOf("shoppingcart") != -1
				|| fileName.indexOf("tempstore") != -1
				|| fileName.indexOf("receiver") != -1
				|| fileName.indexOf("order") != -1
				|| fileName.indexOf("comment") != -1
				|| fileName.indexOf("browHistory") != -1
				|| fileName.indexOf("bookMgr") != -1
				|| fileName.indexOf("commentMgr") != -1	
				|| fileName.indexOf("categoryMgr") != -1	
				|| fileName.indexOf("customerMgr") != -1	
				|| fileName.indexOf("orderMgr") != -1	
				|| fileName.indexOf("managerMgr") != -1	
				
				) {
			chain.doFilter(request, response);
		} else {
			if (hreq.getSession().getAttribute("loginedMgr") == null) {
				hrep.sendRedirect(SysUtils.getSrvPath(hreq)
						+ "/index.jsp");
			} else {

				chain.doFilter(request, response);
				
			}
		
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

//		System.out.println("AuthenticationFilter is init ok now!");
	}

}
